package com.hspedu.houserent.service;

import com.hspedu.houserent.domain.House;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/1/25
 * @time 17:41
 */
public class HouseService {
    private House[] houses;
    private int houseNum = 1;
    private int idCounter = 1;

    public int getHouseNum() {
        return houseNum;
    }

    public HouseService(int length) {
        this.houses = new House[length];
        houses[0] = new House(1, "jack", "110", "北京", 1000, "未出租");
    }

    public boolean addHouse(int id, String hostName, String phoneNum, String address, int rent, String state) {
        House house = new House(id, hostName, phoneNum, address, rent, state);
        if (houseNum == houses.length) {
            resizeArr();
        }
        houses[houseNum++] = house;
        house.setId(++idCounter);
        return true;
    }

    public boolean delHouse(int houseId){
        boolean bool = false;
        for (int i = 0; i < houseNum; i++) {
            if (houseId == houses[i].getId()){
                //从被删除的数据开始
                // 所有数据前移一位覆盖被删除的即可
                forwardData(houses,i);
                bool =  true;
            }
        }
        return bool;
    }

    public House getHouseById(int id){
        for (int i = 0; i < houseNum; i++) {
            if (id == houses[i].getId()){
                return houses[i];
            }
        }
        return null;
    }



    public void forwardData(House[] houses,int i){
        for(int j = i + 1 ; j < houseNum ; j++){
            houses[j - 1] = houses[j];
            //先自减，刚好把最后一位置空，顺带改了houseNum
            houses[--houseNum] = null;
        }
    }

    public void resizeArr() {
        House[] newHouses = new House[(int) (houses.length * 2)];
        for (int i = 0; i < houses.length; i++) {
            newHouses[i] = houses[i];
        }
        houses = newHouses;
    }


    /**
     * 以数组的形式返回所有房屋信息
     *
     * @return House[]
     */
    public House[] list() {
        return this.houses;
    }

    public House[] getHouses() {
        return houses;
    }

    public void updateHouseById( String name, String phoneNum, String address, int rent, String state,int index) {
        houses[index].setHostName(name);
        houses[index].setPhoneNum(phoneNum);
        houses[index].setAddress(address);
        houses[index].setRent(rent);
        houses[index].setState(state);
    }
}
